package cn.com.hbhgkj.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import cn.com.hbhgkj.model.CopyrightApplication;

public class NameValuePairsFactory {

	public List<NameValuePair> createNameValuePairs()
			throws IllegalArgumentException, IllegalAccessException {
		loadValueEntries(this.sourceObj.getClass());
		return buildNameValuePairs();
	}

	private List<NameValuePair> buildNameValuePairs() {

		Object value;
		for (String key : this.fieldValuePairs.keySet()) {
			value = this.fieldValuePairs.get(key);
			addNameValuePair(key, value);
		}

		return this.nameValuePairs;
	}

	private void addNameValuePair(String name, Object value) {
		if (value == null || value.getClass().equals(Class.class))
			return;
		this.nameValuePairs.add(buildNameValuePair(name, value.toString()));
	}

	private NameValuePair buildNameValuePair(String name, String value) {
		return new BasicNameValuePair(name, value);
	}

	private void loadValueEntries(Class<?> clazz)
			throws IllegalArgumentException, IllegalAccessException {

		for (Field f : clazz.getDeclaredFields()) {
			if (!f.isAccessible()) {
				f.setAccessible(true);
			}
			
			IgnoreNameValuePair ignore = f.getAnnotation(IgnoreNameValuePair.class);
			if(ignore == null ){
				
					fieldValuePairs.put(f.getName(), f.get(this.sourceObj));
			}else{
				if(!ignore.ignore()){
					fieldValuePairs.put(f.getName(), ignore.value());
				}
			}
			
			/*if (f.getAnnotation(IgnoreNameValuePair.class) == null)
				fieldValuePairs.put(f.getName(), f.get(this.sourceObj));*/
		}

		Class<?> superClazz = clazz.getSuperclass();

		if (superClazz == null)
			return;
		loadValueEntries(superClazz);
	}

	public List<NameValuePair> getNameValuePairs() {
		return nameValuePairs;
	}

	private final Object sourceObj;
	private final List<NameValuePair> nameValuePairs;

	private final Map<String, Object> fieldValuePairs;

	public NameValuePairsFactory(Object o) {
		this.sourceObj = o;
		this.nameValuePairs = new ArrayList<NameValuePair>();
		this.fieldValuePairs = new HashMap<String, Object>();
	}

	public static void main(String[] args) throws Exception {
		CopyrightApplication ca = new CopyrightApplication();
		ca.setAgentDesc("test");
		ca.setId(1L);

		NameValuePairsFactory f = new NameValuePairsFactory(ca);
		List<NameValuePair> result = f.createNameValuePairs();
		System.out.println(result.size());
	}

}
